#!/bin/bash
set -e

OPENEULER_ROOTFS_IMG=$1

SRC_ROOTFS_DIR=$2
TARGET_ROOTFS_DIR=$3

echo Creating New Rootfs
dd if=/dev/zero of=${OPENEULER_ROOTFS_IMG} bs=1M count=0 seek=6000
mkfs.ext4 ${OPENEULER_ROOTFS_IMG}

echo Mount rootfs to ${TARGET_ROOTFS_DIR}
mkdir -p ${TARGET_ROOTFS_DIR}
mount  ${OPENEULER_ROOTFS_IMG} ${TARGET_ROOTFS_DIR}

echo Copy rootfs to ${TARGET_ROOTFS_DIR}
cp -rfp ${SRC_ROOTFS_DIR}/* ${TARGET_ROOTFS_DIR}

echo Copy Overlay Files...
cp -rfp overlay/* ${TARGET_ROOTFS_DIR}/
cp -rfp libs/* ${TARGET_ROOTFS_DIR}/usr/lib64
cp -rfp include/* ${TARGET_ROOTFS_DIR}/usr/include
cp -rfp rootfs-release ${TARGET_ROOTFS_DIR}/etc

echo Setup Rootfs...
cat << EOF | chroot $TARGET_ROOTFS_DIR

chmod +x /etc/rc.d/rc.local
echo "echo performance > /sys/class/devfreq/dmc/governor" >> /etc/rc.local

EOF

echo Finishing.....
umount ${TARGET_ROOTFS_DIR}

rm -rf ${SRC_ROOTFS_DIR}  ${TARGET_ROOTFS_DIR}

e2fsck -p -f ${OPENEULER_ROOTFS_IMG}
resize2fs -M ${OPENEULER_ROOTFS_IMG}

echo Create ${OPENEULER_ROOTFS_IMG} Done!
